<?php

/*
 * Tomato Framework
 * 
 * Copyright 2012-2012 Luax.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @link http://www.tomatoframework.com
 * @link http://www.luaxlou.com 
 * @version $Id$
 */

/**
 * Description of Load
 *
 * @author luax
 */
class Load {

    private static $instances = array();

    public static function resource($name) {
        $resource = self::_standard_class($name, 'resource');

        $serviceName = $name . 'Service';

        if (property_exists($resource, $serviceName)) {
            $resource->$serviceName = Load::service($name);
        }
        return $resource;
    }

    public static function service($name) {
        $service = self::_standard_class($name, 'service');

        $daoName = $name . 'Dao';

        if (property_exists($service, $daoName)) {
            $service->$daoName = Load::dao($name);
        }
        return $service;
    }

    public static function dao($name) {
        return self::_standard_class($name, 'dao');
    }

    /**
     * 
     * @param type $name
     * @return Pdo
     */
    public static function db($name = null) {

        $instanceName = 'db_' . $name;

        if (!isset(self::$instances[$instanceName])) {

            $config = Config::instance()->get('database');
            $adapter = new PDOAdapter($config);

            self::$instances[$instanceName] = $adapter->getPrototype();
        }

        return self::$instances[$instanceName];
    }

    public static function entity($fileds, $params) {
        
        foreach ($fileds as $key=>$values)
        {
            $fileds[$key] = ""; 
        }
        
        return array_merge($fileds, $params);
    }

    private static function _standard_class($name, $folder) {
        return self::_class(ucfirst($name) . ucfirst($folder), $folder);
    }

    private static function _class($name, $folder) {

        if (isset(self::$instances[$name])) {
            return self::$instances[$name];
        }

        $path = APPLICATION_PATH . '/' . $folder . '/' . $name . '.class.php';

        if (file_exists($path)) {
            require $path;
            return new $name();
        }

        return null;
    }

}

?>
